package com.example.sls.controller.logistics;

import cn.dev33.satoken.stp.StpUtil;
import com.example.sls.pojo.logistics.UserManageTable;
import com.example.sls.pojo.logistics.UserManagement;
import com.example.sls.pojo.user.Users;
import com.example.sls.service.intserfaces.logistics.UserManagementService;
import com.example.sls.service.intserfaces.user.UsersService;
import com.example.sls.utils.LogUtil;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

import static com.example.sls.utils.LogUtil.log;

/**
 * 用户管理表(UserManagement)表控制层
 *
 * @author 蓝江富
 * @since 2024-06-19 13:23:44
 */
@RestController
@RequestMapping("logistics/userManagement")
public class UserManagementController {
  @Autowired
  UserManagementService userManagementService;
  @Autowired
  UsersService usersService;
  @InitBinder
  public void initDateFormate(WebDataBinder dataBinder) {
    dataBinder.addCustomFormatter(new DateFormatter("yyyy-MM-dd HH:mm:ss"));
  }
  @GetMapping("queryById")
  UserManagement queryById(Integer id) {
    return userManagementService.queryById(id);
  }
  @GetMapping("queryAllByLimit")
  List<UserManagement> queryAllByLimit(UserManagement userManagement, Integer pageSize, Integer offset) {
    return userManagementService.queryAllByLimit(userManagement, pageSize, offset);
  }
  @GetMapping("queryAll")
  List<UserManagement> queryAll() {
    return userManagementService.queryAllByLimit(new UserManagement(), 999999, 0);
  }
  // 应前端要求返回表格数据，返回连表查询结果
  @GetMapping("getTableData")
  List<UserManageTable>getTableData(){
    List<UserManageTable>userManageTables=userManagementService.getTableData();
    // 过滤，不提供管理员
    userManageTables.removeIf(
            table ->
                    StpUtil.hasRole(
                            userManagementService.UT_to_UM(table).getUserId(), "admin")
    );
    return userManageTables;
  }
  @GetMapping("count")
  long count() {
    return userManagementService.count();
  }
  @GetMapping("insert")
  int insert(UserManagement userManagement) {
    log(userManagement);
    return userManagementService.insert(userManagement);
  }
  @GetMapping("update")
  int update(UserManageTable userManageTable) {
    UserManagement userManagement = userManagementService.UT_to_UM(userManageTable);
    if (userManagement.getId()==null) {
      userManagementService.insert(userManagement);
      return 1;
    }
    return userManagementService.update(userManagement);
  }
  @GetMapping("deleteById")
  int deleteById(Integer id) {
    return userManagementService.deleteById(id);
  }
}

